//
//  HHYPayAlertView.m
//  大股票
//
//  Created by apple on 2019/9/5.
//  Copyright © 2019 apple. All rights reserved.
//

#import "HHYPayAlertView.h"
#import "HHYHeader.h"

@interface HHYPayAlertView ()<UITextFieldDelegate, UIGestureRecognizerDelegate>

@property (nonatomic, strong) UIView *contentView;
@property (weak, nonatomic) IBOutlet UITextField *codeTF;
@property (weak, nonatomic) IBOutlet UIView *codeView;

@property (nonatomic, strong) UITapGestureRecognizer *hideTap;
@end

@implementation HHYPayAlertView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:self.contentView];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideAction)];
        tap.delegate = self;
        self.hideTap = tap;
        [self addGestureRecognizer:tap];
        
        [self.codeTF becomeFirstResponder];
        self.codeTF.delegate = self;
    }
    return self;
}

- (IBAction)submitAction:(id)sender {
    
    if (self.codeTF.text.length != 6) {
        [HHYUtils textExampleLong:@"请输入6位密码"];
        return;
    }
    
    if (!self.handler) {
        return;
    }
    
    if ([[DGPUtil getZhiFuPwd] isEqualToString:self.codeTF.text]) {
        self.handler(YES, @"");
        [self hideAction];
    } else {
        self.handler(NO, @"支付密码错误");
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (self.codeTF.text.length >= 6&&![string isEqualToString:@""]) {
        return NO;
    }
    return YES;
}

+ (instancetype)showPayAlert {
    HHYPayAlertView *view = [[self alloc] initWithFrame:CGRectMake(0, 0, hhy_kScreenWidth, hhy_kScreenHeight)];
    [[HHYUtils mainWindow] addSubview:view];
    return view;
}

- (void)hideAction {
    [self removeFromSuperview];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if (gestureRecognizer == self.hideTap) {
        CGPoint location = [touch locationInView:self];
        CGRect frame = [self convertRect:self.codeView.frame toView:self];
        if (CGRectContainsPoint(frame, location)) {
            return NO;
        }
    }
    
    return YES;
}

#pragma mark - getter
- (UIView *)contentView {
    if (!_contentView) {
        UINib *nib = [UINib nibWithNibName:@"HHYPayAlertView" bundle:nil];
        NSArray *objs = [nib instantiateWithOwner:self options:nil];
        _contentView = objs[0];
        _contentView.frame = self.bounds;
    }
    return _contentView;
}
@end
